const sections = ['characters', 'locations', 'outlines', 'notes', 'thoughts'];

// 初始化加载数据
window.onload = function () {
    sections.forEach(type => {
        const saved = JSON.parse(localStorage.getItem(type) || '[]');
        saved.forEach(text => addItem(type, text));
    });
};

// 添加项目（带可选默认值）
function addItem(type, value) {
    const input = document.getElementById(type + 'Input');
    const list = document.getElementById(type);

    const content = value || input.value.trim();
    if (!content) return;

    const li = document.createElement('li');
    li.textContent = content;
    list.appendChild(li);

    // 存储到 localStorage
    const saved = JSON.parse(localStorage.getItem(type) || '[]');
    saved.push(content);
    localStorage.setItem(type, JSON.stringify(saved));

    if (!value) input.value = '';
}

// 下载为 JSON 文件
function saveToFile() {
    const data = {};
    sections.forEach(type => {
        data[type] = JSON.parse(localStorage.getItem(type) || '[]');
    });

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'novel-data.json';
    link.click();
    URL.revokeObjectURL(url);
}

// 加载 JSON 文件内容到页面
function loadFromFile(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function (e) {
        const content = JSON.parse(e.target.result);

        // 清除现有内容
        sections.forEach(type => {
            document.getElementById(type).innerHTML = '';
            localStorage.setItem(type, JSON.stringify(content[type] || []));
            (content[type] || []).forEach(text => addItem(type, text));
        });
    };
    reader.readAsText(file);
}
